import { ref, reactive, computed } from "vue"
import { addGroup, getGroup, updateGroup,addMessage,getMessage,updateMessage } from "../../utils/db"
import { getCurrentGroupId, setCurrentGroupId, getHistoryMessages } from "../../utils/ops"

import md from "./data.md?raw"

export class Main {
    constructor() {
        this.initTuijians();
        this.initGroup().then(async () => {
            // await this.initHisMsg();
            await this.initMessage();
        });

    }

    // 开启深度思考
    isThink = ref(false)
    // 开启联网搜索
    isLink = ref(false)
    // 调用接口时的 loading
    loading = ref(false)
    // 是否显示历史会话弹框
    hisDialog = ref(false)
    // 是否显示评价弹框
    commentDialog = ref(false)
    //
    defaultComments = ['有害/不安全','虚假信息','没有帮助','其他']
    // 当前组信息
    current = reactive({ id: "", title: "" })
    // 当前消息集合
    msgs = reactive([])
    // 当前 chat
    chatData = reactive({role:"ROBOT",content:"",thinking_content:"",contentLoading:false,thinkLoading:false,id:""})
    //
    isNew = computed(() => !!this.current.title)
    // 获取最近的一个会话 id
    //----------
    // 推荐列表
    tuijians = reactive([])
    //
    refreshChatData(row){
        Object.assign(this.chatData,row)
        // console.log('this. ===> ',this.chatData)
        setTimeout(() => {
            Object.assign(this.chatData,{role:"ROBOT",content:"",thinking_content:"",contentLoading:false,thinkLoading:false,id:""})
            // console.log('this. ===> ',this.chatData)
        },20)
    }
    // 初始化推荐列表
    async initTuijians(){}
    //
    async initGroup() {
        this.current.id = getCurrentGroupId();
        if (!this.current.id) {
            this.current.id = await addGroup();
            setCurrentGroupId(this.current.id);
        }
        const td = await getGroup(this.current.id)
        this.current.title = td?.title || '';
        //

    }

    async initMessage() {
        if (!this.current.title) return;
        const hisMsgs = await getHistoryMessages(this.current.id);
        let pid = this.msgs.at(-1)?.id || 'root'
        // let ct = 0;
        while (hisMsgs[pid]) {
            // const md = this.msgs[ct];
            const ms = hisMsgs[pid];
            // const mids = ms.map(d => d.id);
            // debugger;
            if (!ms || ms.length == 0) {
                break;
            }
            // if (md && mids && mids.includes(md.id)) {
            //     break;
            // }
            const d = ms.at(-1);
            pid = d.id;
            this.msgs.push({ id:d.id, list: ms.map(t => t.id) })
            // ct++;
            
        }
        console.log('initMessage ---->',this.msgs,hisMsgs)
    }

    // 重新生成 msgs

    

    // 新建会话
    async newChat() {
        if (this.current.title) {
            this.current.id = await addGroup();
            this.current.title = "";
            this.msgs.length = 0;
            setCurrentGroupId(this.current.id);
        }
    }
    // 切换会话
    async changeChat(gid) {
        setCurrentGroupId(gid);
        await this.initGroup();
        await this.initMessage();
    }

    // 删除会话
    async deleteChat(gid) {

    }
    // 修改会话标题
    async upChatTitle(title){
        this.current.title = title;
        await updateGroup(this.current.id, { title })
    }
    
    // 发送聊天
    async send(d) {
        const { content } = d;
        const pid = this.msgs.at(-1)?.id || null;
        const data = { role: "USER", thinking_enabled: this.isThink.value, content, group_id: this.current.id, search_enabled: this.isLink.value, parent_id: pid }
        //
        const id = await addMessage(data)
        const td = await getMessage(id)
        this.msgs.push({id:td.id,data:td,list:[td.id],index:0})
        // 更新分组的标题
        if (pid == null && !this.current.title) {
            updateGroup(this.current.id, { title: content })
            this.current.title = content;
        }
        // 调用接口
        console.log('send =======>')
        const rd = await this.prep(id);
        this.chat(rd)
    }
    // 整理数据
    async prep(pid,sid){
        const parent_id = pid || this.msgs.at(-1).id;
        const data = {role:"ROBOT",group_id:this.current.id,parent_id,content:"",thinking_enabled: this.isThink.value,}
        const id = await addMessage(data)
        const td = {id,...data}
        //
        let i = this.msgs.length;
        if(sid){
            i = this.msgs.map(d => d.id).indexOf(sid);
            this.msgs[i].list.push(id)
            // this.msgs[i].data = td;
            // this.msgs[i].index = this.msgs[i].list.length - 1
            this.msgs[i].id = td.id;
            this.msgs.length = i + 1;
        }else{
            this.msgs.push({id,data:td,list:[id],index:0})
        }
        this.chatData.id = id;
        this.chatData.thinkLoading = true;
        //
        // await this.chat(td)
        return td;
    }
    // 聊天接口 think 数据剥离 状态维护
    async chat(td) {
        // 格式化数据
        //
        
        const f = (k,cb) => {
            const max = Math.random() * 1000 + 100     
            this.chatData[k] = md;
            td[k] = this.chatData[k]
                    cb();
            // const t = setInterval(() => {
            //     if(this.chatData[k].length > max){
            //         clearInterval(t)
            //         td[k] = this.chatData[k]
            //         cb();
            //     }
            //     this.chatData[k] += Math.random().toString(36).replace("0.",'');
            // },50)
        }

        let st = new Date().getTime();

        f('thinking_content',() => {
            const et = new Date().getTime()
            td.thinking_elapsed_secs = (et - st) / 1000
            st = et;
            f('content',async () => {
                td.content_secs = (new Date().getTime() - st) / 1000
                await updateMessage(td.id,td);
                this.chatData.id = "";
                this.chatData.content = "";
                this.chatData.thinking_content = "";
                this.chatData.contentLoading = false;
                this.chatData.thinkLoading = false;
            })
        })
        // 返回数据格式化 
        // const t = setInterval(() => {
        //     if(this.chatData.thinking_content.length > max){
        //         clearInterval(t)
        //         td.content = this.chatData.content;
        //         td.thinking_content = this.chatData.thinking_content;
        //         td.thinking_elapsed_secs = '200 s'
        //         updateMessage(id,td)
        //         this.chatData.mid = "";
        //         this.chatData.content = "";
        //         this.chatData.thinking_content = "";
        //         this.chatData.contentLoading = false;
        //         this.chatData.thinkLoading = false;
                
        //     }

        //     this.chatData.thinking_content += Math.random().toString(36).replace("0.",'');
        // },10)
        // 数据保存
        
    }
    //


    // stop chat
    async stopChat(){}

    // rechat
    async rechat(id){
        const md = await getMessage(id);
        const {parent_id} = md;
        await this.prep(parent_id,id)
    }

    // 修改问题，重新发送
    async upChatContent(i,content,row){
        const {role,group_id,parent_id} = row;
        const data = {role,group_id,parent_id,thinking_enabled: this.isThink.value,search_enabled: this.isLink.value,content}
        const tid = await addMessage(data);
        const td = await getMessage(tid);
        this.msgs.length = i + 1;
        this.msgs[i].list.push(tid);
        // this.msgs[i].data = td;
        this.msgs[i].id = tid;
        // this.msgs[i].index = this.msgs[i].list.length - 1;
        //

    }
    // 修改当前 msg 的 id 左右切换数据的时候会触发
    async upMsgsId(i,ti){
        
        const id = this.msgs[i].list[ti]
        // this.msgs[i].data = td;
        this.msgs[i].id = id;
        // this.msgs[i].index = ti;
        this.msgs.length = i + 1;
        this.initMessage();
    }

    // 获取推荐问题
    async getTuijian(){}

    // 点赞 | 取消点赞
    async userLike(row,val) {
        const id = row.id;
        const comment = val ? '' : row.comment 
        await updateMessage(id,{isLike:val,comment})
    }

    // // 取消点赞
    // async unUserLike(row){
    //     const id = row.id;
    //     await updateMessage(id,{isLike:false})
    //     const td = await getMessage(id)
    //     this.refreshChatData(td);
    // }

    // 点踩 + 评价
    async userComment(row,bool,val = '') {
        
        const id = row.id;
        if(bool){
            await updateMessage(id,{isLike:false,comment:val})
        }
    }

    // 取消点踩 + 删除评价


}